<?php
namespace Home\Controller;

require_once __ROOT__ . '/vendor/riverslei/payment-4.0/autoload.php';

use Payment\Common\PayException;//报错机制
use Payment\Client\Charge;   	//公众号支付类
use Payment\Client\Query;	 	//查询支付的订单
use Payment\Config;          	//配置支付类型

use Lib\Controller\HomeBaseController;

//首页-控制器
class IndexController extends HomeBaseController {

	private $provinceModel;        //省份
    private $cityModel;            //城市
    private $DistrictModel;        //区县
	private $hospitalModel;        //医院
	private $videoBookModel;       //预定订单
	private $videoBookInfoModel;   //订单详情表
    private $errVideoModel;        //错误视频订单
    private $UserModel;            //用户表

    public function __construct(){
        parent::__construct();
        //获取的model作为私有属性
        $this->provinceModel       = D('Province');       //省份
        $this->cityModel           = D('City');           //城市
        $this->DistrictModel       = D('District');       //区县
        $this->hospitalModel       = D('Hospital');       //医院
        $this->videoBookModel      = D('VideoBook');      //预定订单
        $this->videoBookInfoModel  = D('videoBookInfo');  //订单详情
        $this->errVideoModel       = D('errVideo');       //错误视频订单
        $this->UserModel           = D('user');           //用户表

    }

    public function lean_to_buy(){
        $this->display();
    }

    /**
     * 微信获取用户信息
     */
    public function getUserInfo(){
        $login_jump_url = cookie('login_jump_url');cookie('login_jump_url',null);
        if(cookie('userinfo')['id'] == ''){
            $appid = C('WX_APPID');
            $appsecret = C('WX_APPSECRET');
            $code = I('get.code');
            //第一步：获取數據庫的全局access_token 並且判斷是否過期
            $token = $this->_getWXAccessToken();

            //第二步:获取微信用户的openid
            $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
            $oauth2 = $this->wxCurlPost($oauth2Url);

            //第三步:根据全局access_token和openid查询用户信息
            $access_token = $token["access_token"];
            $openid = $oauth2['openid'];
            $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
            $userinfo = $this->wxCurlPost($get_user_info_url);

            //获取jsapi_ticket 全局存
            $get_jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $jsapi_ticket = $this->wxCurlPost($get_jsapi_ticket_url);
            cookie('jsapi_ticket',$jsapi_ticket['ticket']);
            cookie('userinfo',$userinfo);session('userinfo',$userinfo);

            $checkUser = $this->UserModel->where('weixin_openid = "'.$userinfo['openid'].'"')->find();
        }else{
            $userinfo = cookie('userinfo');

            $checkUser = $this->UserModel->where('weixin_openid = "'.$userinfo['weixin_openid'].'"')->find();
        }
        if(!empty($checkUser)){
                //判断用户是否更新的用户名与头像
                if($checkUser['user_name'] != cookie('userinfo')['nickname']){
                    $updateUserData['user_name'] = cookie('userinfo')['nickname'];
                }
                if($checkUser['weixin_avatar'] != cookie('userinfo')['headimgurl']){
                    $updateUserData['weixin_avatar'] = cookie('userinfo')['headimgurl'];
                }
                //如果修改了用户名与头像则更新数据库
                if(isset($updateUserData)){
                    $this->UserModel->where('id = '.$checkUser['id'])->save($updateUserData);
                    $checkUser['user_name'] = $updateUserData['user_name'];
                    $checkUser['weixin_avatar'] = $updateUserData['weixin_avatar'];
                }
                session('userinfo',null);cookie('userinfo',null);
                session('userinfo',$checkUser);cookie('userinfo',$checkUser);
                redirect($login_jump_url);
        }else{
            $this->register(cookie('userinfo'),$login_jump_url);
        }

    }
    /**
     * 注册
     * @param unknown $arr
     */
     public function register($arr,$login_jump_url){
        $userinfo = $arr;
        if($userinfo['id'] != ''){
            $checkUser = $this->UserModel->where('weixin_openid = "'.$userinfo['weixin_openid'].'"')->find();
            if(!empty($checkUser)){
                redirect($login_jump_url);
            }
        }else{
            //获取完微信用户信息后进行用户注册
            $newUserData['weixin_openid'] = $userinfo['openid'];
            $newUserData['weixin_avatar'] = $userinfo['headimgurl'];
            $newUserData['user_name']   = $userinfo['nickname'];
            $newUserData['create_time'] = time();

            $addUserResult = $this->UserModel->add($newUserData);

            $newUserData['id'] = $addUserResult;
            session('userinfo',null);cookie('userinfo',null);
            session('userinfo',$newUserData);cookie('userinfo',$newUserData);
            //添加完毕引导用户录入车辆信息
            redirect($login_jump_url);
        }
    }

    /**
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return string 产生的随机字符串
     */
    public static function getNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    /**
     * [wx_config 微信配置-接口]
     * @author xiezy
     * @date   2017-10-18
     * @return [type]     [description]
     */
    private static function wx_config($decode_url){
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $jsapi_ticket            = cookie('jsapi_ticket');  //获取jsapi_ticket
        $configData['appId']     = C('WX_APPID');           //APPID
        $configData['timeStamp'] = time();                  //签名的时间戳
        $configData['nonceStr']  = static::getNonceStr();   //签名的随机串
        $configData['url']       = $decode_url;             //签名的url（需要和当前页面一模一样）
        $ticket = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$configData['nonceStr'].'&timestamp='.$configData['timeStamp'].'&url='.$configData['url'];
        $configData['signature'] = sha1($ticket);           //签名

        return $configData ? $configData : null;
    }

    /**
     * 样片欣赏【天津baby】
     */
    public function propaganda_vedio(){
        $this->display();
    }

    /**
     * 样片欣赏【梵创科技】
     */
    public function fancon_vedio(){
        $this->display();
    }

    /**
     * [pre_purchase 省份]
     * @author xiezy
     * @date   2018-01-10
     * @return [type]     [description]
     */
    public function pre_purchase(){
    	$city     = $this->cityModel->select();
    	$province = $this->provinceModel->select();
        $district = $this->DistrictModel->select();
        $hospital = $this->hospitalModel->select();

    	$this->assign('city',$city);
        $this->assign('province',$province);
        $this->assign('district',$district);
    	$this->assign('hospital',$hospital);
    	$this->assign('user',cookie('userinfo'));
        $this->display();
    }

    /**
     * [getCityByProvince 获取城市、区县]
     * @author xiezy
     * @date   2018-01-10
     * @return [type]     [description]
     */
    public function getCityByProvince(){
    	$proVal 			 = I('post.proVal');
    	$where['ProvinceID'] = $proVal;
    	$city     			 = $this->cityModel->field('cityid,cityname')->where($where)->select();

        $this->ajaxReturn(array('status'=>1,'info'=>'','data'=>$city));
    }

    /**
     * [getCityByProvince 获取城市、区县]
     * @author xiezy
     * @date   2018-01-10
     * @return [type]     [description]
     */
    public function getHispitalByCity(){
        $where['province_id'] = I('post.proVal');
        $where['city_id']     = I('post.citVal');
        $where['status']      = 1;
        $hospital             = $this->hospitalModel->field('id,hospital_name')->where($where)->select();

        $this->ajaxReturn(array('status'=>1,'info'=>'','data'=>$hospital));
    }

    /**
     * [saveVideoOrder 保存预定订单]
     * @author xiezy
     * @date   2018-01-11
     * @return [type]     [description]
     */
    public function saveVideoOrder(){
    	$saveData 		= I('post.');
    	$ordersn        = date('YmdHis') . str_pad(mt_rand(1, 999999999), 9, '0', STR_PAD_LEFT);  //生成订单号

        //1.订单
    	$saveData['user_id'] 		= cookie('userinfo')['id'];    		//用户id
    	$saveData['ordersn'] 		= $ordersn;    	                    //订单号
    	$saveData['create_time'] 	= time();    	                    //创建时间

    	$priceWhere['id']           = I('post.hospitalID');
    	$saveData['amount']         = $this->hospitalModel->where($priceWhere)->getField('hospital_price');
        $saveData['parents_name']   = $saveData['father_name'];
    	$this->videoBookModel->add($saveData);

        //2.订单详情
        $saveInfoData['ordersn']       = $ordersn;
        $saveInfoData['father_name']   = $saveData['father_name'];
        $saveInfoData['monther_name']  = $saveData['monther_name'];

        //3.查询当前提交预约订单与已存入视频素材是否同一个客户
        $errorWhere['hospital_id']  = $saveData['hospitalID'];
        $errorWhere['hospital_no']  = $saveData['hospitalNO'];
        $errorResult = $this->errVideoModel->where($errorWhere)->find();
        //判断是否有视频存在---防止先录视频后下单的情况
        if ( !empty($errorResult)) {
            $v_num = 4;             //视频数量
            for($x=0;$x<=$v_num-1;$x++){ //最终视频路径-转移到真正下单客户手里
                $saveInfoData['material_video_'.$x] = $errorResult['material_video_'.$x];
            }
            $this->errVideoModel->where($errorWhere)->delete();
        }
        $this->videoBookInfoModel->add($saveInfoData);

    	//跳转到 我的宝贝订单
        $returndata['status'] = 1;
        $returndata['info'] = '预约成功';
        $returndata['url'] = U(MODULE_NAME.'/index/confirm',array('ordersn'=>$ordersn));
        $this->ajaxReturn($returndata);
    }

    /**
     * [confirm 付款页面]
     * @author xiezy
     * @date   2018-01-18
     * @return [type]     [description]
     */
    public function confirm(){
    	//1.获取订单号
    	$ordersn 			= I('get.ordersn');

    	//2.根据订单号查询该订单详情
    	$where['ordersn'] 	= $ordersn;
    	$result             = $this->videoBookModel->where($where)->find();

    	$this->assign('orderData',$result);
        $this->display();
    }

    /**
     * [confirmPay 预定项目视频支付 ]
     * @author xiezy
     * @date   2018-01-18
     * @return [type]     [description]
     */
    public function confirmPay(){
    	$saveData 						= I('post.');

	    //5.组装微信调用支付数据
        $readyData['body']              = C('WX_PAY_body');                            //微信支付body
        $readyData['subject']           = C('WX_PAY_subject');                         //商品名称
        $readyData['order_no']          = $saveData['ordersn'];                        //商户订单号
        $readyData['timeout_express']   = time() + 600;                                //微信600秒支付时间
        $readyData['amount']            = $saveData['amount'];                         //微信支付金额
        $readyData['return_param']      = C('WX_return_param');                        //异步通知原样返回数据
        $readyData['openid']            = cookie('userinfo')['weixin_openid'];         //微信用户openid
        $callpayData = static::payforWx($readyData);
        if (!empty($callpayData['package'])) {
            $jsapi_ticket = cookie('jsapi_ticket'); //获取jsapi_ticket
            $ticket = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$callpayData['nonceStr'].'&timestamp='.$callpayData['timeStamp'].'&url='.C('domain-ly').'/index/confirm/ordersn/'.$saveData['ordersn'].'.html';
            $callpayData['ordersn']   = $saveData['ordersn'];   //帶商戶訂單號
            $callpayData['signature'] = sha1($ticket);          //签名
            $this->ajaxReturn(array('status'=>1,'info'=>'微信支付成功','data'=>$callpayData));
        }else{
            //預支付生成失败,删除数据库订单资料,并关闭订单。
            $this->ajaxReturn(array('status'=>0,'info'=>'微信支付失败','data'=>'error','date'=>$callpayData));
        }
    }

    /**
     * [payforWx 微信调起支付接口所需参数]
     * @author xiezy
     * @date   2017-09-26
     * @param  [array]     $saveData [需要保存的数据]
     * @return [type]                [description]
     */
    private static function payforWx($readyData){

        date_default_timezone_set('Asia/Shanghai');

        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        // 订单信息
        $payData = [
            'body'              => $readyData['body'],              /*商品描述*/
            'subject'           => $readyData['subject'],           /*商品详情*/
            'order_no'          => $readyData['order_no'],          /*商户订单号*/
            'timeout_express'   => $readyData['timeout_express'],   /*表示必须 600s 内付款*/
            'amount'            => $readyData['amount'],            /*单位：元*/
            'return_param'      => $readyData['return_param'],      /*异步通知原样返回数据*/
            'client_ip'         => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',  // 客户地址
            'terminal_id'       =>'WEB',                            /*统一下单-类型*/
            'openid'            => $readyData['openid'],            /*微信用户openid*/
            // 'product_id' => '123',
        ];
        try {
            $ret = Charge::run(Config::WX_CHANNEL_PUB, $wxConfig, $payData);
        } catch (PayException $e) {
            return $e->errorMessage();
            exit;
        }

        return $ret;
    }

    /**
     * [queryforWx 微信查询订单接口]
     * @author xiezy
     * @date   2017-09-26
     * @param  [string]     $ordersn [商户订单号]
     * @return [array]               [查询订单结果集]
     */
    private static function queryforWx($ordersn){

        date_default_timezone_set('Asia/Shanghai');

        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        $data = [
            'out_trade_no' => $ordersn,   //商户订单号
            // 'transaction_id' => '4200000015201709254188440403'  //微信订单号
        ];

        try {
            $ret = Query::run(Config::WX_CHARGE, $wxConfig, $data);
        } catch (PayException $e) {
            echo $e->errorMessage();
            exit;
        }

        return $ret;
    }

    /**
     * [pay_success 支付成功]
     * @author xiezy
     * @date   2018-01-23
     * @return [type]     [description]
     */
    public function notify_info(){
        $where['ordersn'] = I('get.ordersn');

        $data = static::queryforWx($where['ordersn']);
        if ( !empty($data['trade_state']) && $data['trade_state']=='SUCCESS' ) {
            //线上支付需要的订单数据
            $data['is_pay']         = 1;
            $data['pay_time']       = strtotime($data['time_end']); //支付完成时间
            $data['wx_ordersn']     = $data['transaction_id'];      //微信支付订单号
            $this->videoBookModel->where($where)->save($data);
        }

        $this->display('pay_success');
    }



//=========================================================================================================================================

    /**
     * 试看视频的页面↓【暂弃
     */
    public function download_vedio(){
        $this->display();
    }

}
